import {getItem, setItem} from "jvyou-storage-utils";
import {STORAGE_MENUS_KEY} from "@/config/menu-config.ts";
import {IMenu, userMenusAPI} from "@/api/authentication.ts";
import {getToken} from "@/utils/Auth.ts";


export const setMenus = (menus: Array<IMenu>) => setItem(STORAGE_MENUS_KEY, menus, false)
/**
 * 从缓存或者发送请求获取菜单列表
 * 返回Promise
 */
export const getMenus = (): IMenu[] => {
  const menus = getItem(STORAGE_MENUS_KEY, false) || []

  const token = getToken()
  if ((!menus || menus.length <= 0) && token) {
    userMenusAPI().then(res => {
      return res.data || []
    })
  }
  return menus
}

export const findLabelByPath = (menuItems: IMenu[], targetPath: string): string => {
  for (const menuItem of menuItems) {
    if (menuItem.path === targetPath) {
      // 如果找到匹配的 path，返回对应的 label
      return menuItem.label;
    }

    // 如果当前项有子项，则递归查找子项
    if (menuItem.children && menuItem.children.length > 0) {
      const childLabel = findLabelByPath(menuItem.children, targetPath);
      if (childLabel) {
        return childLabel; // 如果在子项中找到匹配的 path，返回对应的 label
      }
    }
  }
  // 如果遍历完整个数组都没有找到匹配的 path，则返回 null 或者其他你认为合适的默认值
  return '';
}




